const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');
const mine = require('./mine.json');

const server = http.createServer((req, res) => {
  res.setHeader('content-type', 'text/html;charset=utf8');

  let urlObj = url.parse(req.url);
  if (urlObj.pathname === '/') {
    // 用流读取文件，性能更好
    let data = fs.createReadStream('./index.html');
    data.pipe(res);
  } else if (urlObj.pathname === '/product') {
    // 一般的读取文件
    let data = fs.readFileSync('product.html');
    res.end(data);
  } else {
    if (urlObj.pathname != '/favicon.ico') {
      // 获取扩展名
      let ext = path.extname(urlObj.pathname);
      res.setHeader('content-type', mine[ext]);
      let source = fs.createReadStream('.' + urlObj.pathname);
      source.pipe(res);
    }
  }
})

server.listen(3000);